package study.chapter03.thread.sync;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();

    }
}

class Ticket implements Runnable{
    int quantity = 5;
    private final ReentrantLock lock = new ReentrantLock();

    public void sale(){
        System.out.println(quantity--);
    }

    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if (quantity > 0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sale();
                }else {
                    break;
                }

            }finally {
                lock.unlock();
            }
        }
    }
}
